package lhy.autoparts.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;

public class Utf8Servlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@Override
    protected void doPost(HttpServletRequest que, HttpServletResponse pon) {
        setEncoding(que, pon);
    }

    @Override
    protected void doGet(HttpServletRequest que, HttpServletResponse pon) {
        setEncoding(que, pon);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
        setEncoding(req, resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) {
        setEncoding(req, resp);
    }
    protected void setEncoding(HttpServletRequest req, HttpServletResponse resp){
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        resp.setContentType("text/html; charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
    }
    //服务端转发请求
    protected void forwardRequest(String target,ServletRequest qu, ServletResponse pon){
        try {
            qu.getRequestDispatcher(target).forward(qu,pon);
        } catch (ServletException | IOException e) {
            e.printStackTrace();
        }
    }
    //客户端跳转
    protected void redirect(String target,HttpServletRequest qu,HttpServletResponse pon){
        try {
            pon.sendRedirect(qu.getContextPath()+"/"+target);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String getPath(HttpServletRequest request){
        String requestURI = request.getRequestURI();
        String contextPath = request.getContextPath();
        String servletPath = request.getServletPath();
        String path = requestURI
                .replaceFirst(contextPath, "")
                .replaceFirst(servletPath, "")
                .replaceFirst("/","");
        return path;
    }
    public static void write(HttpServletResponse resp, Serializable content){
        try {
            resp.setContentType("application/json; charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().print(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
